package com.tanhua.dubbo.api;

import cn.hutool.core.collection.CollUtil;
import com.tanhua.model.mongo.UserLocation;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.Circle;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.Metric;
import org.springframework.data.geo.Metrics;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.geo.GeoJsonPoint;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.List;

@DubboService
public class UserLocationApiImpl implements UserLocationApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override//上报地理位置
    public void save(Long userId, Double latitude, Double longitude, String addrStr) {
        //1.查询当前用户是否存在地理位置
        Criteria criteria = Criteria.where("userId").is(userId);
        Query query = Query.query(criteria);
        boolean exists = mongoTemplate.exists(query, UserLocation.class);
        if (!exists) {
            //3.如果不存在就保存
            UserLocation location = new UserLocation();
            location.setUserId(userId);
            location.setAddress(addrStr);
            location.setCreated(System.currentTimeMillis());
            GeoJsonPoint point = new GeoJsonPoint(longitude, latitude);
            location.setLocation(point);
            mongoTemplate.save(location);
        } else {
            //2.如果存在就更新
            Update update = new Update();
            update.set("location", new GeoJsonPoint(longitude,latitude));
            update.set("address", addrStr);
            update.set("updated", System.currentTimeMillis());
            mongoTemplate.updateFirst(query, update, UserLocation.class);
        }
    }

    @Override//查询附近的人id
    public List<Long> findIds(Long userId, String miles) {
        //查找当前用户的地理位置
        Criteria criteria = Criteria.where("userId").is(userId);
        Query query = Query.query(criteria);
        UserLocation location = mongoTemplate.findOne(query, UserLocation.class);
        //1.获取圆点，获取到当前用户的地理位置
        GeoJsonPoint point = location.getLocation();
        //2.构建半径,两个参数，第一个参数是
        Double value = Double.valueOf(miles);
        Distance distance = new Distance(value/1000, Metrics.KILOMETERS);
        //3.绘制圆
        Circle circle = new Circle(point, distance);
        //构建条件,在已有的位置数据中查询圆覆盖的所有点
        Criteria criteria1 = Criteria.where("location").withinSphere(circle);
        Query query1 = Query.query(criteria1);
        List<UserLocation> list = mongoTemplate.find(query1, UserLocation.class);
        //返回参数
        return CollUtil.getFieldValues(list, "userId", Long.class);
    }
}
